import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { environment } from '../../../../environments/environment';
import { Project } from 'app/ptpmc/model/comm/config-data';
import { CommService } from 'app/ptpmc/comm/comm.service';
import { GlobalDataManager } from 'app/ptpmc/comm/global-data-manager';
import * as Enumerable from 'linq';
import { ReportUrls } from 'app/ptpmc/comm/report.urls.conf';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { UserModel } from '../../../ptpmc/model/sys/user-model';
import { Title } from '@angular/platform-browser';
import { SimpleReuseStrategy } from '../../../ptpmc/components/multytab/multi-tab';
@Component({
    selector: 'app-topnav',
    templateUrl: './topnav_pt.component.html',
    styleUrls: ['./topnav_pt.component.scss']
})
export class TopnavPTComponent implements OnInit {

    // 路由列表
    menuList: Array<{ title: string, module: string, power: string, isSelect: boolean }> = [];

    public projectItems: Project[] = [];
    public projectSelected: Project;
    public curUserName = UserModel.userName;
    constructor(private translate: TranslateService, private commServices: CommService, public router: Router,
        private activatedRoute: ActivatedRoute,
        private titleService: Title) {
        // 路由事件
        this.router.events.filter(event => event instanceof NavigationEnd)
            .map(() => this.activatedRoute)
            .map(route => {
                while (route.firstChild) { route = route.firstChild; };
                return route;
            })
            .filter(route => route.outlet === 'primary')
            .mergeMap(route => route.data)
            .subscribe((event) => {
               
                // 路由data的标题
                const title = event['title'];
                console.log(event)
                if (title == '') {
                    this.commServices.lodingShopSelectedData = true;
                }else {
                    this.commServices.lodingShopSelectedData = false;
                }
                this.menuList.forEach(p => p.isSelect = false);
                const menu = { title: title, module: event['module'], power: event['power'], isSelect: true };
                this.titleService.setTitle('PT | ' + title);
                const exitMenu = this.menuList.find(info => info.title === title);
                if (exitMenu) {// 如果存在不添加，当前表示选中
                    this.menuList.forEach(p => p.isSelect = p.title === title);
                    return;
                }
                this.menuList.push(menu);

                if (this.menuList.length > 5) {
                    this.closeUrl(this.menuList[0].module, false);
                }
            });
    }

    ngOnInit() {
        this.projectItems = Enumerable.from(GlobalDataManager.getProjects()).where(u => u.projectName.toLowerCase() !== 'comm').toArray();
        this.commServices.emitterShop.subscribe(shop => {
            const se = this.projectItems.find(e=>e.projectName == shop)
            if(se){
                this.projectSelected = se;
            }else {
                this.projectSelected = this.projectItems[0];
            }
        })
    }

    // 关闭选项标签
    closeUrl(module: string, isSelect: boolean) {
        // 当前关闭的是第几个路由
        const index = this.menuList.findIndex(p => p.module === module);
        // 如果只有一个不可以关闭
        if (this.menuList.length === 1) { return; };

        this.menuList = this.menuList.filter(p => p.module !== module);
        // 删除复用
        SimpleReuseStrategy.deleteRouteSnapshot(module);
        if (!isSelect) { return; };
        // 显示上一个选中
        let menu = this.menuList[index - 1];
        if (!menu) {// 如果上一个没有下一个选中
            menu = this.menuList[index + 1];
        }
        this.menuList.forEach(p => p.isSelect = p.module === menu.module);
        // 显示当前路由信息
        this.router.navigate(['/' + menu.module]);
    }

    showUrl(module: string) {
        const index = this.menuList.findIndex(p => p.module === module);
        const menu = this.menuList[index];
        this.menuList.forEach(p => p.isSelect = p.module === menu.module);
        // 最近使用的置顶到第一条
        // this.menuList.sort((a, b) => a.isSelect ? 1 : b.isSelect ? 0 : -1);
        this.router.navigate(['/' + menu.module]);
    }

    projectSelectChange(obj: any) {
        ReportUrls.BaseUrl = Enumerable.from(GlobalDataManager.getProjects())
            .where(u => u.projectName === obj.value.projectName).first().apiUrl;
        console.log('选择了车间'+obj.value.projectName)
        this.commServices.onShopSelectedChanged(obj.value.projectName)
        this.commServices.initCommResource();
        GlobalDataManager.projectSelected = Enumerable.from(GlobalDataManager.getProjects())
            .where(u => u.projectName === obj.value.projectName).first();
        // 清除Cycle Time路由
        // console.log('清除路由',this.menuList);
        this.menuList = this.menuList.filter(p => p.module !== 'ptpmc/report/ctd');
        SimpleReuseStrategy.deleteRouteSnapshot('ptpmc/report/ctd');
    }
    toggleSidebar() {
        const dom: any = document.querySelector('body');
        dom.classList.toggle('push-right');
    }

    rltAndLtr() {
        const dom: any = document.querySelector('body');
        dom.classList.toggle('rtl');
    }

    changeLang(language: string) {
        localStorage.setItem('lang', language);
        this.translate.use(language);
    }

    changeTheme(color: string): void {
        let path = '';
        if (environment.production) {
            path = `/themes/app-${color}.css`;
        } else {
            path = `/temp/themes/app-${color}.css`;
        }
        const link = document.createElement('link');
        link.setAttribute('type', 'text/css');
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('href', path);
        document.head.appendChild(link);
    }
    clickPanle(e: any) {
        e.preventDefault();
    }

    exitApp() {
        if (confirm('您是否确认退出？')) {
            this.clearUserInfo();
            this.router.navigate(['']);
            // window.location.reload()
        }
    }

    clearUserInfo() {
        localStorage.clear()
    }
}
